using System;
using System.Collections.Generic;

using OpenTK;

namespace ColladaDotNet.OpenTKMapping
{
	public class Matrix : DocumentLibraryElement<matrix>
	{
		internal override void Load(matrix colladaData)
		{
			base.Load(colladaData);

			if (colladaData.Text.Length < 16)
				throw new ApplicationException("matrix is too short (" + colladaData.Text.Length+" elements)");
		}
		public IList<double> Array
		{
			get
			{
				return Collada.Text;
			}
		}
		public Matrix4d Value4d
		{
			get
			{
				return CreateMatrix4d(Collada.Text, 0);
			}
			set
			{
				Collada.Text = new double[] { value.M11, value.M21, value.M31, value.M41,
				value.M12, value.M22, value.M32, value.M42,
				value.M13, value.M23, value.M33, value.M43,
				value.M14, value.M24, value.M34, value.M44};
			}
		}

		public Matrix4 Value4
		{
			get
			{
				return CreateMatrix4(Collada.Text, 0);
			}
		}

		public static Matrix4d CreateMatrix4d(double[] array, ulong pos)
		{
			return new Matrix4d(array[pos+0], array[pos+4], array[pos+8], array[pos+12],
			array[pos+1], array[pos+5], array[pos+9], array[pos+13],
			array[pos+2], array[pos+6], array[pos+10], array[pos+14],
			array[pos+3], array[pos+7], array[pos+11], array[pos+15]
			);
		}
		public static Matrix4 CreateMatrix4(double[] array, ulong pos)
		{
			return new Matrix4((float)array[pos + 0], (float)array[pos + 4], (float)array[pos + 8], (float)array[pos + 12],
			(float)array[pos + 1], (float)array[pos + 5], (float)array[pos + 9], (float)array[pos + 13],
			(float)array[pos + 2], (float)array[pos + 6], (float)array[pos + 10], (float)array[pos + 14],
			(float)array[pos + 3], (float)array[pos + 7], (float)array[pos + 11], (float)array[pos + 15]
			);
		}

		public static Matrix4d Mult(Matrix4d m, double d)
		{
			return new Matrix4d(m.M11 * d, m.M12 * d,m.M13 * d,m.M14 * d,
				m.M21 * d, m.M22 * d, m.M23 * d, m.M24 * d,
				m.M31 * d, m.M32 * d, m.M33 * d, m.M34 * d,
				m.M41 * d, m.M42 * d, m.M43 * d, m.M44 * d);
		}

		public static Matrix4d Add(Matrix4d m, Matrix4d m2)
		{
			return new Matrix4d(
					m.M11 + m2.M11,
					m.M12 + m2.M12,
					m.M13 + m2.M12,
					m.M14 + m2.M12,
					m.M21 + m2.M21,
					m.M22 + m2.M22,
					m.M23 + m2.M22,
					m.M24 + m2.M22,
					m.M31 + m2.M31,
					m.M32 + m2.M32,
					m.M33 + m2.M32,
					m.M34 + m2.M32,
					m.M41 + m2.M41,
					m.M42 + m2.M42,
					m.M43 + m2.M42,
					m.M44 + m2.M42);
		}
	}
}